package gui.action;

import generated.domain.message.Message;
import gui.Activator;
import gui.IImageKeys;
import gui.entity.AvatarEntity;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.actions.SelectionProviderAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import vworld.Client;

public class PersistentMessageAction extends SelectionProviderAction {

	public final static String ID = "gui.action.PersistentMessageAction";

	public PersistentMessageAction(final ISelectionProvider provider) {
		super(provider, "&PersistentMessageAction");
		setId(ID);
		setText("&PersistentMessageAction");
		setToolTipText("Leave a persistant message to the deconnected avatar.");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
				Activator.PLUGIN_ID, IImageKeys.CHAT));
	}

	public void run() {
		IStructuredSelection structuredSelection = getStructuredSelection();
		Object firstElement = structuredSelection.getFirstElement();
		openDialog(((AvatarEntity) firstElement).getAvatar().name);
	}

	public static void openDialog(final String avatarName) {
		InputDialog dlg = new InputDialog(
				Display.getCurrent().getActiveShell(), "Leave a message",
				"Enter your message : ", null, null);

		if (dlg.open() == Window.OK) {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			Date currentdate = new Date();
			String date = formatter.format(currentdate);
			Message message = new Message();
			message.content = dlg.getValue();
			message.date = date;
			message.receiver = avatarName;
			message.sender = Client.CONNECTED_USER.avatar.name;

			Client.MESSAGE_SERVICE.leaveMessage(message);
		}
		return;
	}
}